--[[
Copyright (c) 2012 Hello!Game

Permission is hereby granted, free of charge, to any person obtaining a copy
of newinst software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and newinst permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
]]

local floor = math.floor;
local random = math.random;
local sqrt = math.sqrt;
local lg = love.graphics;

local Object = getClass("Object");
local Heightmap = class("Heightmap",Object, 
{
	unit_size = 1,

	sun_x = 50,
	sun_y = 50,
	sun_h = 5,
	
	map = nil,
	shadow = nil,
	
	sea_level = .3,
	ice_bound = .8,
});

local function round(num)
	local fn =  floor(num);
	if num-fn>=0.5 then
		return fn+1;
	else
		return fn;
	end
end

local function normalize(value)
	if value > 1 then
		value = 1;
	elseif value < 0 then
		value = 0;
	end
	return value;
end

local function grayColor(v)
	v = v or 0;
	return {255,255,255,255*v}
end

local function plasmaColor(v)
	if v <= 0 then
        return {255,0,0};
    elseif v <= 1/6 then
        return {255, v*6*255, 0};
    elseif v <= 2/6 then
        return {(1-(v - 1/6)*6)*255, 255, 0};
    elseif v <= 3/6 then
        return {0, 255, (v-2/6)*6*255};
    elseif v <= 4/6 then
        return {0, (1-(v-3/6)*6)*255, 255};
    elseif v <= 5/6 then
        return {(v-4/6)*6*255, 0, 255};
    elseif v < 1 then
        return {255, 0, (1-(v-5/6)*6)*255};
    end
    return {255,0,0};
end

local function cloudColor(v)
	if v<=0 then
		return {0,0,255};
	elseif v<1 then
		return {255*v, 255*v, 255}
	end
	return {255,255,255}
end

function Heightmap:initialize(noise)
	self:setNoise(noise);
	
	function self.terrainColor(v)
		local sea_level = self.sea_level;
		local ice_bound = self.ice_bound;
		
		local function colorv (v, start_color, end_color)
			local function cv(v, sc, ec)
				return sc+(ec-sc)*v;
			end
			return {cv(v,start_color[1],end_color[1]),
				cv(v,start_color[2],end_color[2]),
				cv(v,start_color[3],end_color[3])};
		end
		
		if v<sea_level then
			local sc = {0,0,0};
			local ec = {0,0,255};
			local va = v/sea_level;
			return colorv(va, sc, ec);
		elseif v<ice_bound then
			local sc = {0,200,0};
			local ec = {200,0,0};
			local va = (v-sea_level)/(ice_bound-sea_level);
			return colorv(va, sc, ec);
		else
			local sc = {128,128,128};
			local ec = {255,255,255};
			local va = (v-ice_bound)/(1.0-ice_bound);
			return colorv(va, sc, ec);
		end
	end
end

function Heightmap:setNoise(noise)
	self.map = noise or nil;
end

local shadowmap_effect = nil;
local terrain_effect = nil;

function Heightmap.initPixelEffect()
	-- 着色器版本 绘制Shadow
	local shadowmap_sl = [[
extern number sunX;
extern number sunY;
extern number sunZ;
extern number width;
extern number height;

float round(float num)
{
	float fn =  floor(num);
	if(num-fn>=0.5)
		return fn+1;
	else
		return fn;
}

vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords)
{
	float px = texture_coords.x*width;
	float py = texture_coords.y*height;
	float pz = texture2D(texture, texture_coords).a;
	float dx = sunX-px;
	float dy = sunY-py;
	float dz = sunZ-pz;

	float mag = sqrt(dx*dx+dy*dy+dz*dz);
	
	dx = dx/mag;
	dy = dy/mag;
	dz = dz/mag;
	
	while(px>=0 && px<=width && py>=0 && py<=height && pz<=sunZ)
	{
		if (texture2D(texture, vec2(px/width,py/height)).a > pz)
		{
			return color;
		}
		
		px += dx;
		py += dy;
		pz += dz;
	}
	return vec4(color.rgb,0);
}
]]
	shadowmap_effect = lg.newPixelEffect(shadowmap_sl);

-- 着色器版本 绘制Terrain
	local terrain_sl = [[
extern vec3 seacolor_start;
extern vec3 seacolor_end;
extern vec3 treecolor_start;
extern vec3 treecolor_end;
extern vec3 icebound_start;
extern vec3 icebound_end;

extern number sea_level;
extern number ice_bound;

float cv(float v, float sc, float ec)
{
	return (sc+(ec-sc)*v)/255.0;
}

vec4 colorv(float v, vec3 start_color, vec3 end_color)
{
	return vec4(cv(v,start_color.r,end_color.r),
		cv(v,start_color.g,end_color.g),
		cv(v,start_color.b,end_color.b), 1.0);
}

vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords)
{
	float h = texture2D(texture, texture_coords).a;
	
	if(h<sea_level)
		return colorv(h/sea_level, seacolor_start, seacolor_end);
	else if(h<ice_bound)
		return colorv((h-sea_level)/(ice_bound-sea_level), treecolor_start, treecolor_end);
	else
		return colorv((h-ice_bound)/(1.0-ice_bound), icebound_start, icebound_end);
}
]]
	terrain_effect = lg.newPixelEffect(terrain_sl);
	terrain_effect:send("seacolor_start", {0,0,0});
	terrain_effect:send("seacolor_end", {0,0,255});
	terrain_effect:send("treecolor_start", {0,200,0});
	terrain_effect:send("treecolor_end", {200,0,0});
	terrain_effect:send("icebound_start", {128,128,128});
	terrain_effect:send("icebound_end", {255,255,255});

end

Heightmap.initPixelEffect();

function Heightmap:DrawShadow(heightmap, ...)
	shadowmap_effect:send("sunX", self.sun_x);
	shadowmap_effect:send("sunY", self.sun_y);
	shadowmap_effect:send("sunZ", self.sun_h);
	shadowmap_effect:send("width", self.map.width);
	shadowmap_effect:send("height", self.map.height);

	lg.setPixelEffect(shadowmap_effect);
	lg.draw(heightmap, ...);
	lg.setPixelEffect();
end

function Heightmap:DrawTerrain(heightmap, ...)
	terrain_effect:send("sea_level", self.sea_level);
	terrain_effect:send("ice_bound", self.ice_bound);
	
	lg.setPixelEffect(terrain_effect);
	lg.draw(heightmap, ...);
	lg.setPixelEffect();
end

-- 非着实器版本(低速)
function Heightmap:GenShadowMap()
	if self.map==nil then
		return false;
	end

	local mag, dX, dY, dZ;
	local pMag, pX, pY, pZ;
		
	local sunX = self.sun_x;
	local sunY = self.sun_y;
	local sunZ = self.sun_h;
	local ambLight = 0;
	local us = self.unit_size;
	local width = self.map.width;
	local height = self.map.height;
	local map = self.map.noise[0];
	
	self.shadow = {};
	-- 初始化数据
	for i=0, width do
		self.shadow[i] = {};
		for j=0, height do
			self.shadow[i][j] = false;
		end
	end
	
	for x = 0,width,us do
		for y=0,height,us do
			dX = sunX - x;
			dY = sunY - y;
			dZ = sunZ - map[round(x)][round(y)];
			
			mag = sqrt(dX*dX + dY*dY + dZ*dZ);
			
			dX = (dX/mag);
			dY = (dY/mag);
			dZ = (dZ/mag);
			
			pX = x;
			pY = y;
			pZ = map[round(x)][round(y)];
			
			while pX >= 0 and pX <= width and 
				pY >= 0 and pY <= height and pZ <= sunZ do
				
				if map[round(pX)][round(pY)] > pZ then
					self.shadow[x][y] = true;
					break;
				end
				
				pX = pX + (dX * us);
				pY = pY + (dY * us);
				pZ = pZ + (dZ * us);
			end
		end
	end
	
	return true;
end

-- 0:gray 1:plasma 2:cloud 3:terrain
function Heightmap:DrawHeightMap(canvas, mode)
	if self.map==nil then
		return false;
	end
	if canvas==nil then
		return false;
	end
	
	local width = self.map.width;
	local height = self.map.height;
	local map = self.map.noise[0];
	local us = self.unit_size;
	
	canvas:clear();
	local fc = nil;
	if mode==1 then
		fc = plasmaColor;
	elseif mode==2 then
		fc = cloudColor;
	elseif mode==3 then
		fc = self.terrainColor;
	else
		fc = grayColor;
	end
	
	lg.setCanvas(canvas);
    for i=0, width, us do
        for j=0, height, us do
			lg.setColor(fc(map[i][j]));
            lg.rectangle("fill", i, j, us, us);
		end
	end
	lg.setCanvas();
	lg.setColor(255,255,255);
	return true;
end

function Heightmap:DrawShadowMap(canvas, shadow_color)
	if self.shadow==nil then
		return false;
	end
	if canvas==nil then
		return false;
	end
	
	canvas:clear();
	if shadow_color==nil then
		lg.setColor({0,0,0,255});
	else
		lg.setColor(shadow_color);
	end
	
	local width = self.map.width;
	local height = self.map.height;
	local us = self.unit_size;
	
	lg.setCanvas(canvas);
    for i=0, width, us do
        for j=0, height, us do
			if self.shadow[i][j] then
				lg.rectangle("fill", i, j, us, us);
			end
		end
	end
	lg.setCanvas();
	lg.setColor(255,255,255);
	return true;
end

return Heightmap;
